package com.vegetable.modules.controller.finance;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vegetable.common.annotation.SysLog;
import com.vegetable.common.utils.R;
import com.vegetable.modules.entity.baseData.InvoiceInfo;
import com.vegetable.modules.entity.baseData.InvoiceItem;
import com.vegetable.modules.entity.baseData.po.InvoiceAddPO;
import com.vegetable.modules.entity.baseData.po.InvoiceQueryPO;
import com.vegetable.modules.entity.baseData.po.InvoiceUpdatePO;
import com.vegetable.modules.service.baseData.IInvoiceItemService;
import com.vegetable.modules.service.finance.IInvoiceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/invoice")
@Api(value = "发票管理", tags = "发票管理")
public class InvoiceController {
    @Autowired
    private IInvoiceService invoiceService;
    
    @Autowired
    private IInvoiceItemService invoiceItemService;

    @PostMapping("/list")
    @ApiOperation(value = "增值税发票列表", notes = "增值税发票列表")
    public R list(@RequestBody InvoiceQueryPO po) throws IOException {
        Map<String, Object> res = invoiceService.list(po);
        return R.data(res);
    }
    
    @GetMapping("/detail/{id}")
    @ApiOperation(value = "获取发票详情（包含商品明细）", notes = "获取发票详情（包含商品明细）")
    public R detail(@PathVariable Long id) {
        // 获取发票详情（包含商品明细）
        InvoiceInfo invoice = invoiceService.getInvoiceDetailById(id);
        if (invoice == null) {
            return R.fail("发票不存在");
        }
        
        return R.data(invoice);
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存发票", notes = "保存发票")
    public R save(@RequestBody InvoiceAddPO po) throws IOException {
        InvoiceInfo saveInfo = new InvoiceInfo();
        BeanUtils.copyProperties(po, saveInfo);
        invoiceService.saveInvoice(saveInfo);
        return R.data("");
    }

    @SysLog(value = "修改发票归属")
    @PostMapping("/updateInvoiceBelong")
    @ApiOperation(value = "修改发票归属", notes = "修改发票归属")
    public R updateInvoiceBelong(@RequestBody InvoiceUpdatePO po) throws Exception {
        log.info("修改发票归属：{}", po);
        Integer result = invoiceService.updateInvoiceBelong(po);
        return R.success("成功更新" + result + "条发票信息");
    }
}